package repository

import (
	"ginfwk/framework/base"
	"ginfwk/infrastructure/facede"
	"gorm.io/gorm"
)

type IBaseRepository[T any] interface {
	base.IRepository

	SelectById(id interface{}) *T
	SelectOne(query interface{}, args ...interface{}) *T
	SelectByIds(ids interface{}) []*T
	SelectList(query interface{}, args ...interface{}) []*T
}

type BaseRepository[T any] struct {
	base.Repository
}

// 校验接口实现
var _ IBaseRepository[int] = (*BaseRepository[int])(nil)

func (r *BaseRepository[T]) CtxDB() *gorm.DB {
	return facede.CtxDB(r.GetCtx())
}

func (r *BaseRepository[T]) SelectById(id interface{}) *T {
	var t T
	if result := r.CtxDB().First(&t, id); result.Error != nil {
		return nil
	}
	return &t
}

func (r *BaseRepository[T]) SelectOne(query interface{}, args ...interface{}) *T {
	var t T
	if result := r.CtxDB().Where(query, args...).First(&t); result.Error != nil {
		return nil
	}
	return &t
}

func (r *BaseRepository[T]) SelectByIds(ids interface{}) []*T {
	var t []*T
	if result := r.CtxDB().Find(&t, ids); result.Error != nil {
		return nil
	}
	return t
}

func (r *BaseRepository[T]) SelectList(query interface{}, args ...interface{}) []*T {
	var t []*T
	if result := r.CtxDB().Where(query, args...).Find(&t); result.Error != nil {
		return nil
	}
	return t
}
